package com.shqcjd.sinopecdemomobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.InspectionTaskBean;
import com.shqcjd.sinopecdemomobile.model.pojo.IntentEquipmentBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.InspectionTaskAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 巡检任务
 */
public class InspectionTaskActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    private int taskId;
    private InspectionTaskAdapter inspectionTaskAdapter;
    private View notDataView;
    private static final int REQUEST_CODE = 100;
    private Context context;
    private String clickKKS = "";

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_inspection_task;
    }

    @Override
    public void initView() {
        context = this;
        tvToolbarCenter.setText("设备列表");
        taskId = getIntent().getIntExtra("taskId", -1);
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvList.getParent(), false);
        initAdapter();


    }

    private void initAdapter() {
        swipeRefresh.setOnRefreshListener(this);
        inspectionTaskAdapter = new InspectionTaskAdapter();
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setAdapter(inspectionTaskAdapter);
        inspectionTaskAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                InspectionTaskBean.ListBean item = (InspectionTaskBean.ListBean) adapter.getItem(position);
                clickKKS = item.kks;
                if(view.getId()==R.id.ll){
                    if (item.status == 0) {
                        if(item.needScan){
                            RxPermissions permissions = new RxPermissions(InspectionTaskActivity.this);
                            permissions.setLogging(true);
                            permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            if (aBoolean) {
                                                startActivityForResult(new Intent(InspectionTaskActivity.this, QRcodeActivity.class),REQUEST_CODE);
                                            } else {
                                                ToastUtils.show(InspectionTaskActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                            }
                                        }
                                    });
                        }else{
                            if(item.group){
                                Intent it = new Intent(context, EquipmentGroupActivity.class);
                                it.putExtra("kks", item.kks);
                                it.putExtra("tId", taskId);
                                startActivity(it);
                            }else{
                                Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                it.putExtra("kks", item.kks);
                                it.putExtra("tId", taskId);
                                startActivity(it);
                            }
                        }
                    }else{
                        if(item.group){
                            Intent it = new Intent(context, StateInspectionRecordActivity.class);
                            it.putExtra("kks", item.kks);
                            it.putExtra("tId", taskId);
                            startActivity(it);
                        }else{
                            Intent it = new Intent(context, EquipmentInspectionRecordActivity.class);
                            it.putExtra("kks", item.kks);
                            it.putExtra("tId", taskId);
                            startActivity(it);
                        }
                    }
                }else if(view.getId()==R.id.tv_inspection){
                    if (item.status == 0) {//1：已巡检、0：未巡检
                        if(item.needScan){
                            RxPermissions permissions = new RxPermissions(InspectionTaskActivity.this);
                            permissions.setLogging(true);
                            permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) throws Exception {
                                            if (aBoolean) {
                                                startActivityForResult(new Intent(InspectionTaskActivity.this, QRcodeActivity.class),REQUEST_CODE);
                                            } else {
                                                ToastUtils.show(InspectionTaskActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                            }
                                        }
                                    });
                        }else{
                            if(item.group){
                                Intent it = new Intent(context, EquipmentGroupActivity.class);
                                it.putExtra("kks", item.kks);
                                it.putExtra("tId", taskId);
                                startActivity(it);
                            }else{
                                Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                it.putExtra("kks", item.kks);
                                it.putExtra("tId", taskId);
                                startActivity(it);
                            }
                        }
                    }
                }else if(view.getId()==R.id.tv_qcode){
//                    TaskCodeBean taskCodeBean = new TaskCodeBean();
//                    taskCodeBean.user_id = item.user_id;
//                    taskCodeBean.task_id = taskId;
//                    taskCodeBean.kks =item.kks;
//                    QRScanBean bean = new QRScanBean();
//                    Gson gson = new Gson();
//                    bean.json = gson.toJson(taskCodeBean);
//                    bean.sceneType =3;
//                    bean.token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
//                    String json = gson.toJson(bean);
                    Intent intent = new Intent(context, GenerateQRcodeActivity.class);
                    intent.putExtra("QRcode",item.kks);
                    startActivity(intent);
                }
            }
        });

    }

//    @Override
//    public void initData() {
//        getData();
//    }


    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        ApiService.getCheckList(taskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<InspectionTaskBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<InspectionTaskBean> retData) {
                        if (retData.retCode == 10000) {
                            int size = retData.data.list.size();
                            if (size > 0) {
                                inspectionTaskAdapter.setNewData(retData.data.list);
                            } else {
                                inspectionTaskAdapter.setNewData(null);
                                inspectionTaskAdapter.setEmptyView(notDataView);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        showRefreshView(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        showRefreshView(false);
                    }
                });
    }

    public void showRefreshView(Boolean refresh) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refresh);
            }
        });
    }

    @OnClick(R.id.iv_toolbar_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onRefresh() {
        getData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            qCode(value);
        }
    }

    private void qCode(String kksStr){
        if(taskId!=-1){
            if(kksStr.equals(clickKKS)){
                isInspectionData(kksStr);
            }else{
                ToastUtils.showShort(context, "扫描的设备有误");
            }
        }else{
            Toast.makeText(this, "当前网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    private void isInspectionData(String kksStr){
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), taskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取巡检信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if(responseData.retCode==10000){
                            if(responseData.data.check_gps){
                                RxPermissions permissions = new RxPermissions(InspectionTaskActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if(distance<1000){
                                                                if(responseData.data.isgroup){
                                                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", taskId);
                                                                    startActivity(it);
                                                                }else{
                                                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", taskId);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                            }else{
                                                                Toast.makeText(context, "当前位置距离巡检点超过了1000米，请靠近一点再试试", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(InspectionTaskActivity.this, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });
                            }else{
                                hideWaitingDialog();
                                if(responseData.data.isgroup){
                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", taskId);
                                    startActivity(it);
                                }else{
                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                    it.putExtra("tId", taskId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                            }
                        }else{
                            hideWaitingDialog();
                            Toast.makeText(InspectionTaskActivity.this, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(InspectionTaskActivity.this, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }
}
